class Solution {
public:
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int longestIncreasingPath(vector<vector<int>>& matrix)
    {
        int n = matrix.size(), m = matrix[0].size();
        vector<vector<int>> memo(n + 1, vector<int>(m)), vis(n, vector<int>(m));

        function<int(int, int)> dfs = [&](int i, int j) {
            int& res = memo[i][j];
            if (res) return res;
            for (int a = 0; a < 4; a++)
            {
                int x = dx[a] + i, y = dy[a] + j;
                if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && matrix[x][y] > matrix[i][j])
                {
                    res = max(res, dfs(x, y));
                }
            }
            return ++res;
            };

        int ans = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                ans = max(ans, dfs(i, j));
            }
        }
        return ans;
    }
};